package com.example.homework;

import android.content.Intent;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.homework.model.User;

public class RegisterActivity extends AppCompatActivity {
    private EditText nameEdit;
    private EditText passwordEdit;
    private TextView loginButton;
    private Button registerButton;
    private Spinner sexSpinner;
    private DBHelper dbHelper;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register_layout);
        setTitle("注册");
        this.nameEdit=findViewById(R.id.name_edit);
        this.passwordEdit=findViewById(R.id.password_edit);
        this.loginButton=findViewById(R.id.login_button);
        this.registerButton=findViewById(R.id.register_button);
        this.sexSpinner=findViewById(R.id.sex_spinner);
        String[] sexArray=new String[]{"男","女"};
        ArrayAdapter<String> arrayAdapter=new ArrayAdapter<>(this, androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,sexArray);
        this.sexSpinner.setAdapter(arrayAdapter);
        this.sexSpinner.setSelection(0);
        this.dbHelper=new DBHelper(this);

        this.loginButton.setOnClickListener(v->{
            Intent intent=new Intent(this, LoginActivity.class);
            startActivity(intent);
        });
        this.registerButton.setOnClickListener(v->{
            String name=nameEdit.getText().toString();
            String password=passwordEdit.getText().toString();
            String sex=arrayAdapter.getItem(sexSpinner.getSelectedItemPosition());
            User user=dbHelper.findByName(dbHelper.getReadableDatabase(),name);
            if (user!=null){
                Toast.makeText(this,"用户已存在",Toast.LENGTH_SHORT).show();
            }else{
                user=new User();
                user.setName(name);
                user.setPassword(password);
                user.setSex(sex);
                dbHelper.insertUser(dbHelper.getWritableDatabase(),user);
                Toast.makeText(this,"注册成功",Toast.LENGTH_SHORT).show();
            }
        });
    }
}
